﻿/*
 * Copyright 2009-2014 Edward L. Stauff.                  Contact: <EdStauff@gmail.com>.
 * 
 * This file, "Assertion.cs", is part of the "Stauffware.Common.Time" class library.
 * "Stauffware.Common.Time" is free software: you can redistribute it and/or 
 * modify it under the terms of the GNU Lesser Public License as published by the 
 * Free Software Foundation, either version 3 of the License, or (at your option) 
 * any later version.
 * 
 * "Stauffware.Common.Time" is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser Public License for more 
 * details.
 * 
 * You should have received a copy of the GNU Lesser Public License along with 
 * the "Stauffware.Common.Time" sources.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Globalization;
using Stauffware.Common.Core;

#pragma warning disable 1591  // disable warnings for missing XML comments (TEMPORARY)

namespace Stauffware.Common.Time
{
	/// <summary>
	/// Options for parsing dates (but not times; see TimeParseOptions, DateTimeParseOptions).
	/// </summary>
	[Flags]
	public enum DateParseOptions
	{
		None = 0,

		#region ParseOptions compatibility

		/// <summary>
		/// Allow leading whitespace.  (Equal to ParseOptions.AllowLeadingWhite.)
		/// </summary>
		AllowLeadingWhite	= ParseOptions.AllowLeadingWhite,

		/// <summary>
		/// Allow trailing whitespace.  (Equal to ParseOptions.AllowTrailingWhite.)
		/// </summary>
		AllowTrailingWhite	= ParseOptions.AllowTrailingWhite,

		/// <summary>
		/// Allow inner whitespace (but never between digits or time separator).
		/// (Equal to ParseOptions.AllowInnerWhite.)
		/// </summary>
		AllowInnerWhite		= ParseOptions.AllowInnerWhite,

		/// <summary>
		/// Equivalent to combining AllowLeadingWhite, AllowInnerWhite, and AllowTrailingWhite.
		/// (Equal to ParseOptions.AllowWhiteSpace.)
		/// </summary>
		AllowWhiteSpace		= ParseOptions.AllowWhiteSpace,

		/// <summary>
		/// Forces parsing of the entire input string.
		/// Without this option, extraneous characters following a valid time will
		/// terminate the parsing, but not cause an error.
		/// (Equal to ParseOptions.ParseEntireInput.)
		/// </summary>
		ParseEntireInput	= ParseOptions.ParseEntireInput,

		#endregion


		AdjustToUniversal		= 0x0010,
		AssumeLocal				= 0x0020,
		AssumeUniversal			= 0x0040,
		RoundtripKind			= 0x0080,


		/// Interpret ambiguous day and month numbers as day preceding month.
		DayMonthWhenAmbiguous	= 0x0100,
		/// Interpret ambiguous day and month numbers as month preceding day.
		MonthDayWhenAmbiguous	= 0x0200,
		/// Numeric month must follow day number, even if unambiguous; e.g. "4/31" is not allowed.
		DayMonthStrict			= 0x0400,
		/// Numeric month must precede day number, even if unambiguous; e.g. "31/4" is not allowed.
		MonthDayStrict			= 0x0800,

		/// Allow use of keywords "yesterday", "today", "tomorrow".
		AllowToday				= 0x1000,
		/// Allow dates consisting of a day name with keywords "last", "next".
		AllowRelativeDayOfWeek	= 0x2000,
		/// Allow dates consisting of only a day name; defaults to the date nearest to today.
		DefaultDayToNearestDate	= 0x4000,
		/// Allow dates without years; defaults year to whatever date is nearest to today.
		DefaultYearToNearestDate = 0x8000,
	}

	//#################################################################################
	/// <summary>
	/// A parser for dates (but not times; see TimeParse, DateTimeParse).
	/// Constructing a DateParser is fairly expensive, so try to re-use them where possible.
	/// </summary>
	/// <remarks>
	/// This implementation is a temporary hack.
	/// </remarks>

	public class DateParser
	{
		/// <summary>
		/// Enum bits reserved for DateParseOptions.  
		/// "Derived" parse option enums must not redefine these.
		/// </summary>
		internal const int Reserved_ParseOptions_Bits = 0xFFFF00;

		/// <summary>
		/// What to use when there isn't a DateParseOptions parameter.
		/// </summary>
		public const DateParseOptions DefaultParseOptions = 
				DateParseOptions.AllowWhiteSpace | DateParseOptions.ParseEntireInput;

		private readonly DateParseOptions Options;

		private readonly IFormatProvider FormatProvider;

		private static string[] FormatStrings =
		{
			// Every permutation of: (year month day | day month year | month day year) x 
			//		("yy" | "yyyy") x ("M | "MM" | "MMM" | "MMMM") x ("d" | "dd") x ("/" | "-" | " ")
			// Plus every permutation of: 
			//		("yy" | "yyyy") x ("MMM" | "MMMM") x ("d" | "dd") for DMY with separator = "" 
			// Generated by GenerateDatePatterns() in UnitTests (_Program.cs).

			@"yy M d",          @"M d yy",          @"d M yy",
			@"yy-M-d",          @"M-d-yy",          @"d-M-yy",
			@"yy\/M\/d",        @"M\/d\/yy",        @"d\/M\/yy",
			@"yy M dd",         @"M dd yy",         @"dd M yy",
			@"yy-M-dd",         @"M-dd-yy",         @"dd-M-yy",
			@"yy\/M\/dd",       @"M\/dd\/yy",       @"dd\/M\/yy",
			@"yy MM d",         @"MM d yy",         @"d MM yy",
			@"yy-MM-d",         @"MM-d-yy",         @"d-MM-yy",
			@"yy\/MM\/d",       @"MM\/d\/yy",       @"d\/MM\/yy",
			@"yy MM dd",        @"MM dd yy",        @"dd MM yy",
			@"yy-MM-dd",        @"MM-dd-yy",        @"dd-MM-yy",
			@"yy\/MM\/dd",      @"MM\/dd\/yy",      @"dd\/MM\/yy",
			@"yy MMM d",        @"MMM d yy",        @"d MMM yy",
			@"yy-MMM-d",        @"MMM-d-yy",        @"d-MMM-yy",
			@"yy\/MMM\/d",      @"MMM\/d\/yy",      @"d\/MMM\/yy",		@"dMMMyy",
			@"yy MMM dd",       @"MMM dd yy",       @"dd MMM yy",
			@"yy-MMM-dd",       @"MMM-dd-yy",       @"dd-MMM-yy",
			@"yy\/MMM\/dd",     @"MMM\/dd\/yy",     @"dd\/MMM\/yy",		@"ddMMMyy",
			@"yy MMMM d",       @"MMMM d yy",       @"d MMMM yy",
			@"yy-MMMM-d",       @"MMMM-d-yy",       @"d-MMMM-yy",
			@"yy\/MMMM\/d",     @"MMMM\/d\/yy",     @"d\/MMMM\/yy",		@"dMMMMyy",
			@"yy MMMM dd",      @"MMMM dd yy",      @"dd MMMM yy",
			@"yy-MMMM-dd",      @"MMMM-dd-yy",      @"dd-MMMM-yy",
			@"yy\/MMMM\/dd",    @"MMMM\/dd\/yy",    @"dd\/MMMM\/yy",	@"ddMMMMyy",
			@"yyyy M d",        @"M d yyyy",        @"d M yyyy",
			@"yyyy-M-d",        @"M-d-yyyy",        @"d-M-yyyy",
			@"yyyy\/M\/d",      @"M\/d\/yyyy",      @"d\/M\/yyyy",
			@"yyyy M dd",       @"M dd yyyy",       @"dd M yyyy",
			@"yyyy-M-dd",       @"M-dd-yyyy",       @"dd-M-yyyy",
			@"yyyy\/M\/dd",     @"M\/dd\/yyyy",     @"dd\/M\/yyyy",
			@"yyyy MM d",       @"MM d yyyy",       @"d MM yyyy",
			@"yyyy-MM-d",       @"MM-d-yyyy",       @"d-MM-yyyy",
			@"yyyy\/MM\/d",     @"MM\/d\/yyyy",     @"d\/MM\/yyyy",
			@"yyyy MM dd",      @"MM dd yyyy",      @"dd MM yyyy",
			@"yyyy-MM-dd",      @"MM-dd-yyyy",      @"dd-MM-yyyy",
			@"yyyy\/MM\/dd",    @"MM\/dd\/yyyy",    @"dd\/MM\/yyyy",
			@"yyyy MMM d",      @"MMM d yyyy",      @"d MMM yyyy",
			@"yyyy-MMM-d",      @"MMM-d-yyyy",      @"d-MMM-yyyy",
			@"yyyy\/MMM\/d",    @"MMM\/d\/yyyy",    @"d\/MMM\/yyyy",	@"dMMMyyyy",
			@"yyyy MMM dd",     @"MMM dd yyyy",     @"dd MMM yyyy",
			@"yyyy-MMM-dd",     @"MMM-dd-yyyy",     @"dd-MMM-yyyy",
			@"yyyy\/MMM\/dd",   @"MMM\/dd\/yyyy",   @"dd\/MMM\/yyyy",	@"ddMMMyyyy",
			@"yyyy MMMM d",     @"MMMM d yyyy",     @"d MMMM yyyy",
			@"yyyy-MMMM-d",     @"MMMM-d-yyyy",     @"d-MMMM-yyyy",
			@"yyyy\/MMMM\/d",   @"MMMM\/d\/yyyy",   @"d\/MMMM\/yyyy",	@"dMMMMyyyy",
			@"yyyy MMMM dd",    @"MMMM dd yyyy",    @"dd MMMM yyyy",
			@"yyyy-MMMM-dd",    @"MMMM-dd-yyyy",    @"dd-MMMM-yyyy",
			@"yyyy\/MMMM\/dd",  @"MMMM\/dd\/yyyy",  @"dd\/MMMM\/yyyy",	@"ddMMMMyyyy"
		};

		//-----------------------------------------------------------------------------
		/// <summary>
		/// Constructs a parser that uses DefaultParseOptions.
		/// </summary>
		public DateParser ( ) : this(DefaultParseOptions, null) { }

		/// <summary>
		/// Constructs a parser.
		/// </summary>
		/// <param name="options">parsing options</param>
		public DateParser (DateParseOptions options) : this(options, null) { }

		/// <summary>
		/// Constructs a parser that uses DefaultParseOptions.
		/// </summary>
		/// <param name="ifp">formatting info, or null</param>
		public DateParser (IFormatProvider ifp) : this(DefaultParseOptions, ifp) { }

		//-----------------------------------------------------------------------------
		/// <summary>
		/// Constructs a parser.
		/// </summary>
		/// <param name="options">parsing options</param>
		/// <param name="ifp">format provider</param>

		public DateParser (DateParseOptions options, IFormatProvider ifp)
		{
			this.Options = options;

			if (ifp != null)
				this.FormatProvider = ifp;
			else
				this.FormatProvider = CultureInfo.InvariantCulture;

			Require.Condition(options.HasFlag(DateParseOptions.ParseEntireInput),
					"sorry, current temporary implementation can't do partial strings");
		}

		//-----------------------------------------------------------------------------
		/// <summary>
		/// Parses a date.  
		/// Should never throw an exception except for failed assertions (programming errors).
		/// </summary>
		/// <param name="input">the string to be parsed</param>
		/// <returns>
		///		The result of the parse attempt, whether successful or not; will never return null.
		/// </returns>

		public DateParse Parse (string input)
		{
			// TEMPORARY IMPLEMENTATION while I try to get my own from-scratch code working.

			DateParse parse = new DateParse();

			parse._parsedText = input;

			if (this.Options.HasFlag(DateParseOptions.AllowLeadingWhite))
				input = input.TrimStart();
			if (this.Options.HasFlag(DateParseOptions.AllowTrailingWhite))
				input = input.TrimEnd();

			if (input == "")
			{
				Ensure.Condition(parse.IsEmpty);
				return parse;
			}

			try
			{
			//	parse._value = DateTime.Parse(input);
				parse._value = DateTime.ParseExact(input, FormatStrings, this.FormatProvider, 
																		DateTimeStyles.None);
			}
			catch (FormatException e)
			{
				parse._errorMessage = e.Message;
			}

			return parse;
		}

		//-----------------------------------------------------------------------------
	}

	//#################################################################################
	/// <summary>
	/// Encapsulates the result of trying to parse a date from a string into a DateTime,
	/// whether successful or unsuccessful.  Does not include a time; see DateTimeParse.
	/// </summary>
	/// <remarks>
	/// This implementation is a temporary hack.
	/// </remarks>

	public class DateParse : ValueParse<DateTime>
	{
	}

	//#################################################################################
}
